<template>
  <el-dialog v-model="visible" :title="title" @close="cancel" width="25%">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px">
      <el-form-item label="关键词" prop="value">
        <el-input v-model="dataForm.value"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel()">取消</el-button>
      <el-button type="primary" @click="submit()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { addKeywordConfig, editKeywordConfig } from '@/api/allApi'

const emit = defineEmits(['resetList'])

const visible = ref(false)
const title = ref('新增')
const dialogType = ref('add')
const dataFormRef = ref()
const dataForm = reactive({
  value: ''
})
const dataRules = reactive({})
const rowDate = reactive({})

const init = (type: string, row: any) => {
  visible.value = true
  dialogType.value = type
  Object.assign(rowDate, row) // 浅拷贝，将 row 赋值给 rowDate，用以前直接 = 赋值的形式会报错
  switch (type) {
    case 'add':
      title.value = '新增'
      break
    case 'edit':
      title.value = '修改'
      // 回显
      for (let key in dataForm) {
        dataForm[key] = row[key]
      }
      break
    default:
      break
  }
}

const submit = () => {
  let api = addKeywordConfig
  let obj = {
    ...dataForm,
    tenantId: JSON.parse(localStorage.getItem('userInfo')).id, // 租户id
    websiteId: Number(localStorage.getItem('WebsiteId')) // 网站id
  }

  switch (dialogType.value) {
    case 'add':
      api = addKeywordConfig
      obj.creator = JSON.parse(localStorage.getItem('userInfo')).id
      break
    case 'edit':
      api = editKeywordConfig
      obj.updater = JSON.parse(localStorage.getItem('userInfo')).id
      obj.id = rowDate.id
      break
    default:
      break
  }

  api(obj).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success('操作成功')
      emit('resetList')
      cancel()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const cancel = () => {
  visible.value = false
  dataFormRef.value.resetFields()
}

defineExpose({
  init
})
</script>
